package com.adobe.crypto
{
	
	import flash.utils.ByteArray;
	
	/**
	 * CRC32校验算法类
	 *
	 * @Author DuskEye
	 * @langversion 3.0
	 * @productversion 1.0
	 */
	
	public class CRC32
	{
		// CRC32算法的查找表
		private static const crc32Table:Array = createCRC32Table();
		
		/**
		 * 计算CRC32校验码
		 * @param data 待计算的数据
		 * @return 校验值
		 */
		public static function hash(data:ByteArray):uint
		{
			var crc:uint = 0xFFFFFFFF; // 初始值为0xFFFFFFFF
			for (var i:int = 0; i < data.length; i++)
			{
				crc = (crc >>> 8) ^ crc32Table[(crc ^ data[i]) & 0xFF];
			}
			return crc ^ 0xFFFFFFFF; // 取反得到最终结果
		}
		
		private static function createCRC32Table():Array
		{
			var table:Array = [];
			var poly:uint = 0xEDB88320; // CRC32多项式
			for (var i:uint = 0; i < 256; i++)
			{
				var crc:uint = i;
				for (var j:uint = 0; j < 8; j++)
				{
					crc = (crc & 1) ? (crc >>> 1) ^ poly : crc >>> 1;
				}
				table[i] = crc;
			}
			return table;
		}
	}
}